// pages/mapindex/mapindex.js
var app = getApp(); //获取应用实例
var mapCtx = null;
const defaultScale = 14;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    latitude: 32.041546,
    longitude: 118.76741,
    mapScale: defaultScale,
    enabelpoi: false,
    markers: null,
    circles: null,
    curMarker: null,
    showSearchBar: true,
    showMapContral: true,
    detailShow: false,
    likes: 0,
    like: false,
    likeCreate: true,
    windowHeight: "",
    windowWidth: "",
    inputFocus: false,
    showData: null,
    cursor: 0,
    isCityListOpen: false,
    currentCity: app.globalData.city.currentCity,
    cityList: app.globalData.city.cityList,
    topics: app.globalData.topic.topics,
    topicKeys: app.globalData.topic.topicKeys,
    topicIndex: app.globalData.topic.topicIndex,
    keyword: ''
  },
  onReady: function (e) {
    // 使用 wx.createMapContext 获取 map 上下文
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline']
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _this = this;
    _this.mapCtx = wx.createMapContext("mymap");
    let cityKey = _this.data.currentCity;
    _this.requestMarkers(cityKey);
    _this.mapCtx.on('markerClusterClick', res => {
      console.log('markerClusterClick', res)
    })
    // 使用默认聚合效果时可注释下一句
    _this.bindClusterEvent()
  },
  /**
   * 获取marker数据
   */
  requestMarkers(cityKey) {
    let _this = this;
    let markers = wx.getStorageSync(cityKey);
    // let markers = null;
    if (markers && markers.length > 0) {
      console.log("cache markers...", markers);
      _this.setData({
        markers: markers,
      });
      _this.mapCtx.addMarkers({
        markers,
        clear: true,
        complete(res) {
          console.log('update markers form cache~', res)
        }
      })
    } else {
      let url = app.baseUrl + "/data/" + cityKey + ".json";
      if (cityKey == '全部') {
        url = "https://api.atlasdata.cn/mock/redmap/data/culster.json";
        console.log('全部聚合点~url:', url);
      }

      wx.request({
        url: url,
        success: function (res) {
          if (res.data.RECORDS && res.data.RECORDS.length > 0) {
            //刷新数据
            const markers = res.data.RECORDS;
            markers.forEach((marker) => {
              if (cityKey == '全部') {
                marker.iconPath = "/statics/images/cluster-icon-e.png";
                let id = marker.id
                marker.id = id + 9999;
                marker.joinCluster = true;
                marker.callout = {
                  content: marker.name + '\n' + marker.count,
                  textAlign: 'center',
                  color: "#444",
                  fontSize: 14,
                  bgColor: '#fafafa00',
                  anchorY: 48,
                  display: "ALWAYS",
                };
                // marker.label = {
                //   content: marker.name + '\n' + marker.count,
                //   textAlign: "center",
                //   color: "#444",
                //   fontSize: 14,
                //   // bgColor: "#fafafa",
                //   anchorX: marker.name.length > 2 ? -21 : -14,
                //   anchorY: -50,
                // }
                marker.width = 64;
                marker.heigth = 64;
                marker.latitude = parseFloat(marker.latitude);
                marker.longitude = parseFloat(marker.longitude);
                return marker;

              } else {
                marker.iconPath = app.baseUrl + '/icons/' + marker.imgurl + '.png';
                marker.imgurl = app.baseUrl + '/pres/' + marker.imgurl + '.jpg';
                marker.joinCluster = true;
                let labelx = marker.name;
                let split = labelx.length / 2
                if (labelx.length > 9) {
                  labelx = labelx.slice(0, parseInt(split)) + "\n" + labelx.slice(parseInt(split));
                  split = Math.ceil(split);
                } else {
                  split = labelx.length;
                }
                marker.callout = {
                  content: labelx,
                  textAlign: "center",
                  color: "#444444",
                  fontSize: 11,
                  borderWidth: 1,
                  borderRadius: 12,
                  borderColor: "#eeeeee00",
                  bgColor: "#fafafa",
                  padding: 6,
                  // anchorX: -(split * 11) / 2 + 'rpx',
                  anchorY: labelx.length > 9 ? 100 : 88,
                  display: "ALWAYS",
                };
                marker.width = 64;
                marker.heigth = 64;
                marker.latitude = parseFloat(marker.latitude);
                marker.longitude = parseFloat(marker.longitude);
                return marker;
              }

            });

            console.log(markers)
            _this.setData({
              markers: markers,
            });
            _this.mapCtx.addMarkers({
              markers,
              clear: true,
              complete(res) {
                console.log('update markers from server~', res)
              }
            })


            // 存储位置数据于缓存中
            wx.setStorage({
              key: cityKey,
              data: markers,
            });
          }
        },
        fail: function (err) {
          console.log("onload fail→", err);
        },
        complete: function () {
          console.log("onload complete...");
        },
      });
    }
  },
  /**
   * 选择主题
   */
  pickerChange(e) {
    let _this = this;
    let index = e.detail.value;
    let topicKey = _this.data.topicKeys[index];
    _this.setData({
      topicIndex: index,
    });
    if (index >= 0 && index < _this.data.topics.length) {
      _this.requestMarkers(topicKey);
    }
  },
  /**
   * 选择省份
   */
  tapSelectCity: function (e) {
    let _this = this;
    console.log(e)
    if (e.currentTarget.dataset.name) {
      let cityKey = e.currentTarget.dataset.name;
      console.log("点击了省，", cityKey)
      _this.setData({
        isCityListOpen: false,
        currentCity: cityKey,
      });
      _this.requestMarkers(cityKey)
    } else {
      let id = e.detail.markerId
      let cityKey = this.data.cityList[id - 9999];
      console.log("点击了聚合点，", cityKey)
      _this.setData({
        isCityListOpen: false,
        currentCity: cityKey,
        markers: []
      });
      _this.mapCtx.addMarkers({
        markers: [],
        clear: true,
        complete(res) {
          console.log('update markers from server~', res)
        }
      })
      _this.requestMarkers(cityKey)
    }

  },
  /**
   * 打开省份列表
   */
  tapOpenCityList: function () {
    let searchList = this.data.showData;
    if (!this.data.isCityListOpen && searchList) {
      searchList = null;
    }
    this.setData({
      isCityListOpen: !this.data.isCityListOpen,
      showData: searchList,
    });
  },
  /**
   * 输入变化/失去焦点进行搜索
   */
  onBlurSearch: function (e) {
    let citylist = this.data.isCityListOpen;
    if (citylist) {
      citylist = false;
    }
    let showData = new Array();
    let searchdata = this.data.markers;
    if (e.detail.cursor >= this.data.cursor) {
      let inputData = e.detail.value.replace(/(^\s*)|(\s*$)/g, "");
      if (inputData.length > 1) {
        let limit = 9;
        for (var i in searchdata) {
          if (searchdata[i].name.indexOf(inputData) != -1) {
            let marker = searchdata[i];
            showData.push(marker);
            if (i > limit) {
              break;
            }
          }
        }
        this.setData({
          showData: showData,
          isCityListOpen: citylist,
        });
      }
    } else {
      this.setData({
        showData: null,
      });
    }
    this.data.cursor = e.detail.cursor;
  },
  onSearch: function (e) {
    console.log(this.data.keyword)
  },
  /**
   * 缩放至搜索列表项
   */
  zoomToSearchItem(e) {
    let opts = e.currentTarget.dataset;
    this.setData({
      showData: null,
      latitude: opts.lat,
      longitude: opts.lng,
      mapScale: defaultScale,
    });
    this.mapCtx.moveToLocation();
  },
  /**
   * 地图点击事件
   */
  maptap(e) {
    this.setData({
      isCityListOpen: false,
      showData: null,
    });
  },
  /**
   * marker点击事件
   */
  markertap(e) {
    let _this = this;
    // 选中 其对应的框
    let id = e.detail.markerId
    console.log("e.detail.markerId:", id);
    if (id > 9999) {
      this.tapSelectCity(e);
      //marker找不到，则为聚合点,直接走城市选择路线
      // let cityKey = this.data.cityList[-id];
      // console.log("点击了聚合点，", cityKey)
      // _this.setData({
      //   isCityListOpen: false,
      //   currentCity: cityKey,
      //   markers: []
      // });
      // _this.mapCtx.addMarkers({
      //   markers: [],
      //   clear: true
      // })
      // _this.requestMarkers(cityKey)
      // return;
    } else {
      let marker = this.data.markers.find((item) => item.id == id);
      _this.setData({
        curMarker: marker,
        detailShow: true,
        showSearchBar: false,
        showMapContral: false,
        isCityListOpen: false,
      })
      const db = wx.cloud.database();
      wx.showLoading({
        title: '',
      })
      //获取点赞数量
      db.collection('likes').where({
          id: marker.id,
          like: 1,
        }).count()
        .then(res => {
          _this.setData({
            likes: res.total,
            like: false,
          })
        })

      let like = 0; //默认不显示点赞
      let likeCreate = false; //默认不创建新记录
      //获取本人有没有点赞
      db.collection('likes').where({
          id: marker.id,
          _openid: app.openid,
        }).get()
        .then(res => {
          if (res.data.length) {
            like = res.data[0].like
          } else {
            likeCreate = true;
          }
          _this.setData({
            like: like,
            likeCreate: likeCreate
          })
          wx.hideLoading()
        }).catch((e) => {
          wx.hideLoading()
        });
    }
  },
  /**
   * 定位到我的位置
   */
  zoomTolocation() {
    var _this = this;
    wx.getLocation({
      type: "gcj02", // 默认为 wgs84 返回 gps 坐标，gcj02 返回可用于 wx.openLocation 的坐标
      success: function (res) {
        app.globalData.latitude = res.latitude;
        app.globalData.longitude = res.longitude;
        _this.setData({
          longitude: res.longitude,
          latitude: res.latitude,
        });
        _this.mapCtx.moveToLocation();
      },
      fail: function (err) {
        console.log("err→", err);
      },
    });
  },
  /**
   * 打开关闭poi
   */
  enablePoi: function () {
    this.setData({
      enabelpoi: !this.data.enabelpoi,
    });
  },
  /**
   * 放大
   */
  zoomIn: function (e) {
    let zoom = this.data.mapScale;
    if (zoom < 20) {
      zoom++;
    }
    this.setData({
      mapScale: zoom,
    });
    console.log("zoomIn→", zoom);
  },
  /**
   * 缩小
   */
  zoomOut: function (e) {
    console.log(e);
    let zoom = this.data.mapScale;
    if (zoom > 3) {
      zoom--;
    }
    this.setData({
      mapScale: zoom,
    });
    console.log("zoomOut→", zoom);
  },
  /**
   * 点赞
   */
  likeIt: function (event) {
    let _this = this;
    let like = _this.data.like;
    let likeCreate = _this.data.likeCreate;
    let likes = _this.data.likes;
    const db = wx.cloud.database();
    if (like) {
      //取消点赞
      db.collection('likes')
        .where({
          id: _this.data.curMarker.id
        })
        .update({
          data: {
            like: 0,
          }
        }).then(res => {
          likes--;
          _this.setData({
            likes: likes,
            like: 0
          })
        });
    } else {
      //记录点赞
      if (likeCreate) {
        db.collection('likes')
          .add({
            data: {
              id: _this.data.curMarker.id,
              name: _this.data.curMarker.name,
              iconPath: _this.data.curMarker.iconPath,
              like: 1,
            }
          }).then(res => {
            likes++;
            _this.setData({
              likes: likes,
              like: 1,
            })
          });
      } else {
        db.collection('likes')
          .where({
            id: _this.data.curMarker.id
          })
          .update({
            data: {
              like: 1,
            }
          }).then(res => {
            likes++;
            _this.setData({
              likes: likes,
              like: 1,
              likeCreate: false,
            })
          });
      }
    }
  },
  /**
   * 分享
   */
  goToShare() {
    let _this = this;
    wx.navigateTo({
      url: "/pages/share/share?name=" +
        _this.data.curMarker.name +
        "&imgUrl=" +
        _this.data.curMarker.imgurl,
    });
  },
  /**
   * 聚类回调
   */
  bindClusterEvent() {
    let _this = this;
    _this.mapCtx.initMarkerCluster({
      enableDefaultStyle: false,
      zoomOnClick: true,
      gridSize: 128,
      complete(res) {
        console.log('initMarkerCluster', res)
      }
    })

    // enableDefaultStyle 为 true 时不会触发改事件
    _this.mapCtx.on('markerClusterCreate', res => {
      const clusters = res.clusters
      const markers = clusters.map(cluster => {
        const {
          center,
          clusterId,
          markerIds
        } = cluster;
        let iconUrl = "/statics/images/cluster-icon.png";
        return {
          ...center,
          width: 64,
          height: 64,
          iconPath: iconUrl,
          clusterId, // 必须
          label: {
            content: markerIds.length.toString(),
            color: "#ffffff",
            fontSize: 14,
            width: 28,
            height: 28,
            bgColor: '#e52b2b',
            borderRadius: 28,
            textAlign: 'center',
            anchorX: 12,
            anchorY: -64,
          }
        }
      })
      _this.mapCtx.addMarkers({
        markers,
        clear: false,
        complete(res) {
          console.log('clusterCreate addMarkers', res)
        }
      })
    })
  },
  /**
   * 关闭详情页
   */
  closeDetail() {
    this.setData({
      detailShow: false,
      showSearchBar: true,
      showMapContral: true,
    });
  },
  //发送到朋友
  onShareAppMessage: function () {
    return {
      title: "中国革命纪念馆坐标",
      path: '/pages/mapindex/mapindex',
      imageUrl: '/statics/bg/share.png',
    }
  },
  //发送到朋友圈
  onShareTimeline() {
    return {
      title: "中国革命纪念馆坐标",
      imageUrl: '/statics/bg/share.png',
    }
  }
});